
// UDP相关变量
WiFiUDP Udp;
const int udpPort = 6060; // 与发送端监听端口对应
bool UdpkStatus = false;

// UDP循环函数
void loopUdp()
{
    static bool startUdp = false;
    static uint32_t loopUdpTick = 0;
    if (WiFi.status() == WL_CONNECTED && millis() - loopUdpTick > 2000)
    {
        if (!startUdp)
        {
            Udp.begin(udpPort); // UDP初始化
            startUdp = true;
        }
        int packetSize = Udp.parsePacket();
        if (packetSize)
        {
            char buff[255];
            Udp.read(buff, packetSize);
            buff[packetSize] = '\0'; // 确保字符串以'\0'结尾

            // Serial.println(buff);

            // 解析数据并赋值给相应变量
            if (sscanf(buff,
                       "电池电压:%f\n电池电流:%f\n电池温度:%f\n电池电量:%f\n充电电压:%f\n充电电流:%f\n光伏电压:%f\n光伏电流:%f\n光伏功率:%f\n累计功率 :%f\n控制器温度:%f\n",
                       &batteryVoltage, &batteryCurrent, &batteryTemperature, &batteryCharge, &chargeVoltage, &chargeCurrent, &pvVoltage, &pvCurrent, &pvPower, &cumulativePower, &controllerTemperature) == 11)
            {
                // Serial.println("数据解析成功");
                // sendtoData(buff);
                UdpkStatus = true;
                batteryPower = batteryCurrent * batteryVoltage;
            }
            else
            {
                // Serial.println("数据解析失败");
                UdpkStatus = false;
            }
        }
        else
        {
            UdpkStatus = false;
        }

        loopUdpTick = millis();
    }
}
